import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/user'

NProgress.configure({ showSpinner: false });

const whiteList = ['/login'];

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.meta.title) {
      document.title = to.meta.title + ' - ' + import.meta.env.VITE_APP_TITLE
    } else {
      document.title = import.meta.env.VITE_APP_TITLE
    }
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (useUserStore().permissions.length === 0) {
        useUserStore().getInfo().then(() => {
          next({ ...to, replace: true })
        }).catch(err => { })
      } else {
        next()
      }
    }
  } else {
    document.title = import.meta.env.VITE_APP_TITLE
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
